package cn.com.klun.tjy.other.ThreadsTest;


import java.util.ArrayList;
import java.util.List;

public class ThreadCommunicate {
    // 1. 共享内存式通讯
    // 2. while轮询的方式
    private List<String> list = new ArrayList<>();
    public void add(){
        list.add("elements");

    }
    public int size(){
        return list.size();
    }

    Thread A  =  new Thread(new Runnable() {
        private ThreadCommunicate list;

        public ThreadCommunicate getList() {
            return list;
        }
        public void setList(ThreadCommunicate list) {
            this.list = list;
        }

        @Override
        public void run() {
            try{
                for (int i = 0; i < 10; i++) {
                    list.add();
                    System.out.println("添加了"+(i+1)+"个元素");
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    });
    Thread B  =  new Thread(new Runnable() {
        private ThreadCommunicate list;

        public ThreadCommunicate getList() {
            return list;
        }
        public void setList(ThreadCommunicate list) {
            this.list = list;
        }

        @Override
        public void run() {
            try {
                while (true){
                    if(list.size() == 5){
                        System.out.println("==5,线程B准备退出了");
                            throw new InterruptedException();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    public static void main(String[] args) {

    }
}
class A{
    synchronized public void methodA(){
        System.out.println("同步方法A");
    }
    synchronized public void methodB(){
        System.out.println("同步方法B");
    }
}




